<?php
// Copyright 2019 Hackware SpA <human@hackware.cl>
// This file is part of "Hackware Web Services Wallet" and licensed under
// the terms of the GNU Affero General Public License version 3, or (at your
// option) a later version. You should have received a copy of this license
// along with the software. If not, see <https://www.gnu.org/licenses/>.

namespace Hawese\Wallet;

use Hawese\Core\Exceptions\ModelObjectNotFoundException;

class PartialPayment extends TableModel
{
    const AMOUNT_P = 8;

    public static $table = 'partial_payments';
    public static $attributes = [
        'transaction_id' => [ // foreign and primary! o_O
            'required', 'integer', 'min:1', 'exists:transactions,id'
        ],
        'amount' => ['required', 'regex:/^-?\d{1,8}(?:\.\d{1,8})?$/'],
        'created_at' => ['nullable', 'date'],
        'updated_at' => ['nullable', 'date']
    ];

    public static $primary_key = 'transaction_id';
    protected static $incrementing = false;
    public static $foreign_keys = ['transaction_id' => Transaction::class];

    /**
     * Updates or create an initial PartialPayment.
     */
    public static function addOrCreate(
        int $transaction_id,
        string $amount
    ): self {
        try {
            $partial_payment = self::find($transaction_id);
            $partial_payment->amount = bcadd(
                $partial_payment->amount,
                $amount,
                self::AMOUNT_P
            );
            $partial_payment->update(['amount']);
        } catch (ModelObjectNotFoundException $e) {
            $partial_payment = new self([
                'transaction_id' => $transaction_id,
                'amount' => $amount,
            ]);
            $partial_payment->insert();
        }

        return $partial_payment;
    }
}
